<template>
    <div class="count-box">
        <button @click="handlesub">-</button>
        <input type="text" :value="value" @change="handleChange">
        <button @click="handleadd">+</button>
    </div>
</template>

<script>
export default {
    props: {
        value: {
            type: Number,
            default: 1
        },
    },
    methods: {
        // 减
        handlesub() {
            if (this.value <= 1) return
            this.$emit('input', this.value - 1)
        },
        // 加
        handleadd() {
            this.$emit('input', this.value + 1)

        },
        handleChange(e) {
            // 判断输入框的值是否非数值 或负数，若是 则回退其初始值
            const num = +e.target.value

            if (isNaN(num) || num < 1) {
                e.target.value = this.value
                return
            }
            this.$emit('input', num)
        }
    },
}
</script>

<style lang="less" scoped>
.count-box {
    display: flex;
    width: 200px;
    height: 40px;
    justify-content: center;
    align-items: center;

    button,
    input {
        height: 100%;
        margin-bottom: 0;
        margin: 0 5px;
        text-align: center;
        background-color: #ddd;
        color: #333;
    }

    input {
        width: 40px;
    }

    button {
        width: 20px;
    }
}
</style>